<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>shader动画</title>
</head>
<body>
  <script src="../common/lib/gl-renderer.js"></script>
  <canvas width="512" height="512"></canvas>
  <script type="module">
    import {Animator} from '../common/lib/animator/index.js';
    const vertex = `
      attribute vec2 a_vertexPosition;
      attribute vec2 uv;

      varying vec2 vUv;

      void main() {
        gl_PointSize = 1.0;
        vUv = uv;
        gl_Position = vec4(a_vertexPosition, 1, 1);
      }
    `;
    const fragment = `
      #ifdef GL_ES
      precision highp float;
      #endif

      varying vec2 vUv;
      uniform vec4 color;
      uniform float rotation;

      void main() {
        vec2 st = 2.0 * (vUv - vec2(0.5));
        float c = cos(rotation);
        float s = sin(rotation);
        mat3 transformMatrix = mat3(
          c, s, 0,
          -s, c, 0,
          0, 0, 1
        );
        vec3 pos = transformMatrix * vec3(st, 1.0);
        float d1 = 1.0 - smoothstep(0.5, 0.505, abs(pos.x));
        float d2 = 1.0 - smoothstep(0.5, 0.505, abs(pos.y));
        gl_FragColor = d1 * d2 * color;
      }
    `;
    const canvas = document.querySelector('canvas');
    const renderer = new GlRenderer(canvas);
    const program = renderer.compileSync(fragment, vertex);
    renderer.useProgram(program);
    renderer.uniforms.color = [1, 0, 0, 1];
    renderer.uniforms.rotation = 0.0;

    const animator = new Animator({duration: 2000, iterations: Infinity});
    animator.animate(renderer, ({target, timing}) => {
      target.uniforms.rotation = timing.p * 2 * Math.PI;
    });

    renderer.setMeshData([{
      positions: [
        [-1, -1],
        [-1, 1],
        [1, 1],
        [1, -1],
      ],
      attributes: {
        uv: [
          [0, 0],
          [0, 1],
          [1, 1],
          [1, 0],
        ],
      },
      cells: [[0, 1, 2], [2, 0, 3]],
    }]);
    renderer.render();
  </script>
</body>
</html>